package com.wang.observer;

import java.util.ArrayList;
import java.util.List;

public class Subject {

    private List<ObServer> list = new ArrayList<>();
    private int state;

    public void setState(int state){
        this.state = state;
        notifyAllObServer();
    }

    public int getState(){
        return this.state;
    }

    public void attach(ObServer obServer){
        this.list.add(obServer);
    }

    public void notifyAllObServer(){
        for(ObServer obServer: this.list){
            obServer.update();
        }
    }

    public static void main(String[] args) {
        Subject subject = new Subject();
        new ObserverA(subject);
        new ObserverB(subject);
        System.out.println("state == 10::::");
        subject.setState(10);
        System.out.println("state == 12::::");
        subject.setState(12);
    }

}

abstract class ObServer{
    Subject subject;
    public abstract void update();
}

class ObserverA extends ObServer{

    public ObserverA(Subject subject){
        this.subject = subject;
        this.subject.attach(this);
    }

    @Override
    public void update() {
        System.out.println("观察者模式——1::::"+this.subject.getState());
    }
}

class ObserverB extends ObServer{

    public ObserverB(Subject subject){
        this.subject = subject;
        this.subject.attach(this);
    }

    @Override
    public void update() {
        System.out.println("观察者模式——2::::"+this.subject.getState());
    }
}
